import { useMemo, useContext } from 'react';
import { Descendant, createEditor } from 'slate';
import { Slate, withReact, Editable } from 'slate-react';
import { withHistory } from 'slate-history';
import styles from './Editor.module.less';
import { appContext } from '../config/context';
import { initialValue } from './text';
import Heading from '@/plugins/heading';
import UnorderedList from '@/plugins/unordered-list';
import Integration from '@/core/plugins';
import Shortcut from '@/plugins/shortcut';
import Quote from '@/plugins/quote';
import CodeBlock from '@/plugins/code-block';
import Bold from '@/plugins/bold';
import Italic from '@/plugins/italic';
import UnderLine from '@/plugins/underline';
import Strikethrough from '@/plugins/strikethrough';
import InLineCode from '@/plugins/inline-code';
import Align from '@/plugins/align';
import StyleBase from '@/plugins/style-base';
import Indent from '@/plugins/indent';
import HoveringToolbar from './HoveringToolbar';

function Editor_() {
  const editor = useMemo(() => withHistory(withReact(createEditor())), []);
  const { readonly } = useContext(appContext);

  function onChange(value: Descendant[]) {
    console.log(value);
  }

  const { renderElement, onKeyDown, decorate, renderLeaf } = useMemo(() => {
    const pl = new Integration(
      Heading(editor),
      UnorderedList(editor),
      Quote(editor),
      CodeBlock(editor),
      Bold(),
      Italic(),
      UnderLine(),
      Strikethrough(),
      InLineCode(),
      Align(),
      StyleBase(),
      Indent(editor)
    );
    const commands = pl.getCommand();
    pl.addPlugin(Shortcut(editor, commands));
    return pl.start();
  }, [editor]);

  return (
    <>
      <Slate editor={editor} initialValue={initialValue} onChange={onChange}>
        <HoveringToolbar />
        <Editable
          className={styles.Editor}
          decorate={decorate}
          renderElement={renderElement}
          renderLeaf={renderLeaf}
          readOnly={readonly}
          placeholder="请开始你的表演..."
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          onKeyDown={onKeyDown}
        ></Editable>
      </Slate>
      <div className={styles.footer}>后续支持完善中...</div>
    </>
  );
}

export default Editor_;
